<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/10/27
 * Time: 10:16
 */

namespace zhtfrontend\modules\sitepadapi\controllers;

use backend\modules\sysappapi\components\rest\ActiveController;
use common\components\helpers\Fun;
use common\components\helpers\Util;
use yii\data\ArrayDataProvider;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use yii\web\ForbiddenHttpException;
use yii\web\HttpException;
use yii\web\NotFoundHttpException;
use yii\web\Response;

class CollectController extends ActiveController
{
    public $modelClass = 'common\models\datas\Customer';

    public $serializer = [
        'class' => 'zhtfrontend\modules\sitepadapi\components\rest\Serializer',
        'collectionEnvelope' => 'items',
    ];

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;
        return $behaviors;
    }

    public function actions()
    {
        $actions = parent::actions();
        unset($actions['index'], $actions['create'], $actions['update'], $actions['delete'], $actions['view']);
        return $actions;
    }

    public function actionCreate($user_id, $sales_id)
    {
        $site_id=Fun::getSiteId();
        $this->getSiteDb($site_id);
        $data = \Yii::$app->request->post();
        $remark = ArrayHelper::keyExists('remark', $data) ? $data['remark'] : '';
        $dataArr = [
            'customer_id' => $user_id,
            'sales_id' => $sales_id,
            'remark' => $remark,
            'created_at' => time(),
            'status' => 1
        ];
        $result = (new Query())->select('*')->from('{{%collect}}')->where(['customer_id' => $user_id, 'sales_id' => $sales_id])->one();
        if (empty($result)) {
            \Yii::$app->db->createCommand()->insert('{{%collect}}', $dataArr)->execute();
            $lastInsertId = \Yii::$app->db->lastInsertID;
            return $this->findModel($lastInsertId, $site_id);
        }else{
            if($result['status']==1){
                try{
                    throw new ForbiddenHttpException('您已该课程已收藏');
                }catch (HttpException $e){
                    return ['status' => 0, 'message' => 'error', 'result' => $e->getMessage()];
                }
            }
            if($result['status']==0){
                \Yii::$app->db->createCommand()
                    ->update('{{%collect}}', ['status' => 1], ['customer_id' => $user_id, 'sales_id' => $sales_id])->execute();
                return $result;
            }
        }
    }

    public function actionList($site_id, $customer_id)
    {
        $this->getSiteDb($site_id);
        $collect = (new Query())->select('*')->from('{{%sales}} s')
            ->leftJoin('{{%collect}} c', 's.id=c.sales_id')
            ->leftJoin('{{%course}} co', 's.course_id=co.id')
            ->leftJoin('{{%teacher}} t', 's.teacher_id=t.id')
            ->where(['c.customer_id' => $customer_id])
            ->groupBy('c.customer_id')
            ->all();
        foreach ($collect as $k => $v) {
            $data[] = [
                'collect_id' => $v['id'],
                'image' => $v['img'],
                'course_name' => $v['title'],
                'teacher_name' => $v['name'],
                'course_modality' => Util::getModality($v['teache_form'])
            ];
        }
        return new ArrayDataProvider([
            'allModels' => $data,
            'pagination' => ['pageSize' => 20]
        ]);
    }

    public function actionUpdate($site_id, $collect_id)
    {
        $this->getSiteDb($site_id);
        \Yii::$app->db->createCommand()->update('{{%collect}}', ['status' => 0], ['id' => $collect_id])->execute();
        return $this->findModel($collect_id, $site_id);
    }

    public function findModel($id, $site_id)
    {
        $this->getSiteDb($site_id);
        $model = (new Query())->select('*')->from('{{%collect}}')->where(['id' => $id])->one();
        if (empty($model)) {
            try {
                throw new NotFoundHttpException('信息不存在');
            } catch (NotFoundHttpException $e) {
                return ['status' => 0, 'message' => 'error', 'result' => $e->getMessage()];
            }
        } else {
            return $model;
        }
    }

    protected function getSiteDb($site_id)
    {
        $site_cache = Fun::cache('site_cache');
        foreach ($site_cache as $k => $v) {
            if ($site_id == $v['id']) {
                $site = $v['domain'];
            }
        }
        if ($site == null) return false;
        if (!isset($site_cache[$site])) return false;
        if (!isset($site_cache[$site]['db'])) return false;
        \Yii::$app->set('db', $site_cache[$site]['db']);
    }
}